package com.example.shirospringboot.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.mgt.SessionStorageEvaluator;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.mgt.DefaultWebSessionStorageEvaluator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
    @Value("${passwordHashIterations}")
    private int passwordHashIterations;
    
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition(){
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/login", DefaultFilter.anon.name());
        //完成对token的拦截登录工作
        chainDefinition.addPathDefinition("/**", DefaultFilter.authcBearer.name());
        
        return chainDefinition;
    }
    
    @Bean
    public SessionStorageEvaluator sessionStorageEvaluator() {
        DefaultWebSessionStorageEvaluator defaultWebSessionStorageEvaluator = new DefaultWebSessionStorageEvaluator();
        defaultWebSessionStorageEvaluator.setSessionStorageEnabled(false);
        return defaultWebSessionStorageEvaluator;
    }
    
    
    /**
     * 比较传入的密码和数据库的密码是否一致
     * 这里定义了密码加密的一些内容
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(Md5Hash.ALGORITHM_NAME);
        hashedCredentialsMatcher.setHashIterations(passwordHashIterations);
        return hashedCredentialsMatcher;
    }
    
    
    /**
     * 解决我们自定义了Realm后无法启动的问题
     * https://blog.csdn.net/qq_34741165/article/details/83720666
     * @return
     */
    @Bean
    public Authorizer authorizer() {
        ModularRealmAuthorizer authorizer = new ModularRealmAuthorizer();
        return authorizer;
    }
    

}
